<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Banner;
use app\common\model\City;
use app\common\model\Coupon;
use app\common\model\coupon\Log;
use app\common\model\Evaluation;
use app\common\model\Hospital;
use app\common\model\MoneyLog;
use app\common\model\Notice;
use app\common\model\ScoreLog;
use app\common\model\Service;
use app\common\model\service\Order;
use app\common\model\service\order\Info;
use app\common\model\ServiceCategory;
use app\common\model\User;
use app\common\model\user\Jz;
use app\common\model\UserGroup;
use app\common\model\Wxpay;
use PDOException;
use think\Db;
use think\db\Query;
use think\Exception;
use think\Queue;

/**
 *服务订单接口
 */
class ServiceOrder extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 服务订单下单
     *
     */
    public function orderAdd()
    {
        $uid = $this->auth->id;
        $params = request()->param();
        $params['user_id'] = $uid;
        extract($params);
        if (!isset($cate_id) || !$cate_id) {
            $this->error('请选择预约服务');
        }
//        if (!isset($hospital_id) || !$hospital_id) {
//            $this->error('请选择医院');
//        }
        if (!isset($jz_id) || !$jz_id) {
            $this->error('请选择就诊人');
        }
        if (!isset($actiontime) || !$actiontime) {
            $this->error('请选择就诊时间');
        }
        Db::startTrans();
        try {
            Jz::updateDefault($params);
            $service = Service::get($cate_id);
            $order = Order::addOrder($params, $service);
            if ($order) {
                $res = Info::addData($order, $service->time);
                Queue::later(1800, 'app\common\job\Order', $order, 'order');
            }
            Db::commit();
            //实付金额为0
            if ($order['pay_amount'] <= 0) {
                $order->save(['status' => 1]);
                $this->success('支付成功', $res, 2);
            }

        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('请求成功', $res);
    }
    /**
     * 服务订单续费
     *
     */
    public function orderRenewal()
    {
        $params = request()->param();
        extract($params);
        if (!isset($params['time']) || empty($params['time'])) {
            $this->error('续费时间不能为空');
        }
        if (!Order::get($params['id'])) {
            $this->error('主订单不存在');
        }

        //判断是否有未支付续费订单
        if (Info::whereNull('paytime')->where('order_id', $params['id'])->find()) {
            $this->error('用户当前存在未支付的追加服务费，请稍后重试');
        }
        Db::startTrans();
        try {
            $order = Info::orderRenewal($params);
            Queue::later(900, 'app\common\job\OrderRenewal', $order, 'renewal');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('请求成功', $order->id);
    }
    /**
     * 服务订单列表
     *
     */
    public function list()
    {
        $uid = $this->auth->id;
        $params = request()->param();
        extract($params);
        $order = new Order;
        if ($status == 'all') {
            $order->where('order.status', '<>', '-1');
        } elseif ($status == 2) {
            $order->whereIn('order.status', ['1']);
        }  elseif ($status == 1) {
            $order->whereIn('order.status', ['2']);
        } else {
            $order->where('order.status', $status);
        }
        $list = $order->with(['info', 'category', 'hospital', 'service', 'jz', 'escort'])->where('order.user_id', $uid)->order('id desc')->paginate(10);

        $this->success('请求成功', $list);
    }
    /**
     * 服务订单详情
     *
     */
    public function info()
    {
        $params = request()->param();
        extract($params);
        $order = new Order;
        $info = $order->get($id, ['info', 'category', 'hospital', 'service', 'jz', 'escort']);
        $info['total_renew_time'] = Info::where(['order_id' => $info['id'], 'status' => 1])->whereNull('paytime')->where('renewal_amount', '>', 0)->sum('time');
        $info['total_renew_amount'] = Info::where(['order_id' => $info['id'], 'status' => 1])->whereNull('paytime')->where('renewal_amount', '>', 0)->sum('renewal_amount');
        $this->success('请求成功', $info);
    }

    /**
     * 服务订单评价
     *
     */
    public function evaluation()
    {
        $params = request()->param();
        extract($params);
        $data = new Evaluation();
        if (!isset($order_id) || !$order_id) {
            $this->error('订单错误');
        }
        if (!isset($escort_id) || !$escort_id) {
            $this->error('陪诊师错误');
        }
        if (!isset($content) || !$content) {
            $this->error('请输入评价内容');
        }
        if (!isset($evaluation)) {
            $this->error('请选择评价');
        }
        $params['user_id'] = $this->auth->id;
        $params['escort_id'] = $escort_id;

        $data->allowField(true)->save($params);

        //更新陪诊师评价率
        $total_evaluation = Evaluation::where(['escort_id' => $escort_id])->count();
        $good_evaluation = Evaluation::whereIn('evaluation', [1, 2])->where('escort_id', $escort_id)->count();
        $comment_ratio = number_format($good_evaluation / $total_evaluation * 100);
        $carers = User::get($escort_id);
        $carers->comment_ratio = $comment_ratio;
        $carers->save();

        $this->success('评价成功');
    }

    /**
     * 立即付款
     *
     */
    public function pay()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            $order = Info::get($id);
            if ($order['renewal_amount'] <= 0) {
                $orderInfo = Order::get($order->order_id);
                if ($order->status == 1) {
                    $escort = User::get($orderInfo->escort_id);
                    $group = UserGroup::column('id,proportion');
                    $proportion = $group[$escort->group_id];
                    $commission = bcmul($orderInfo->total_amount, bcdiv($proportion, 100, 2), 2);
                }
                $order->save(['paytime' => time(), 'commission' => $commission ?? 0]);
                if ($orderInfo->status == 0) {
                    $orderInfo->save(['code' => code(), 'status' => '1']);
                    $mark = "您已成功预约，请按时到达预定地点";
                    $this->auth->template_push($orderInfo['id'], 0, $mark);
                } else {
                    $orderInfo->save([
                        'total_amount' => $orderInfo->total_amount + $order->renewal_amount,
                        'pay_amount' => $orderInfo->pay_amount + $order->renewal_amount,
                        'commission' => $orderInfo->commission + $commission,
                    ]);
                }
            } else {
                $uid = $this->auth->id;
                $userInfo = User::get($uid);
                $sdk = Wxpay::wxpay($order->sn, $order['renewal_amount'], $userInfo['openid'], $attach);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('提交支付失败：' . $e->getMessage());
        }
        $this->success('', $sdk ?? []);
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        $info = new Info;
        Db::startTrans();
        try {
            $info = $info->get($id);
            $order = Order::get($info->order_id);
            if ($order->status == '0') {
                Order::cancelOrder($order);
            } else {
                Wxpay::refund($info);
            }
            Db::commit();
        } catch (PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage() . '-' . $e->getLine());
        }
        $this->success('取消成功');
    }
    /**
     * 开始订单
     */
    public function startOrder()
    {
        $post = $this->request->post();
        extract($post);
        $order = new Order;
        $order = $order->get(['escort_id' => $this->auth->id, 'code' => $code]);
        if (!$order) {
            $this->error('订单错误');
        }
        if ($order['status'] != 2) {
            $this->error('订单状态错误');
        }
        $res = $order->save(['status' => 3, 'servicetime' => time()]);
        if ($res) {
            $this->success('服务开始');
        }
        $this->error('失败');
    }
    /**
     * 订单验收
     */
    public function acceptance()
    {
        $post = $this->request->post();
        extract($post);
        $order = new Order;
        $order = $order->get(['user_id' => $this->auth->id, 'id' => $id]);
        if (!$order) {
            $this->error('订单错误');
        }
        if ($order['status'] != 3) {
            $this->error('订单状态错误');
        }
        Db::startTrans();
        try {
            $res = $order->save(['status' => 4, 'endtime' => time()]);
            if ($res) {
                $user = User::get($order->user_id);
                //上级积分分佣
                if ($user->pid) {
                    $point = bcdiv($order->pay_amount, config('site.score_ratio'), 0);
                    if ($point > 0) {
                        ScoreLog::income($user->pid, $point, 2, 200, $order->total_sn);
                    }
                }
                //陪诊师佣金
                $escort = User::get($order->escort_id);
                $group = UserGroup::column('id,proportion');
                $proportion = $group[$escort->group_id];
                $pro = bcmul($order->total_amount, bcdiv($proportion, 100, 2), 2);
                MoneyLog::income($order->escort_id, $pro, 2, 100, $order->total_sn);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('失败:' . $e->getMessage());
        }
        $this->success('验收成功');
    }
}
